package org.io4j.resource;

import java.io.InputStream;
import java.net.URL;

import org.io4j.InputOutputException;
import org.io4j.filesystem.File;
import org.io4j.filesystem.FileSystemException;
import org.io4j.filesystem.Path;
import org.io4j.util.Argument;

/**
 * A {@code Resource} that can be found in the file system.
 */
public class FileResource extends BaseResource {

	private final File file;

	/**
	 * Constructs a {@code FileResource} from a {@code File}.
	 * 
	 * @throws IllegalArgumentException
	 *            if file is {@code null}
	 */
	public FileResource(File file) {
		Argument.isNotNull(file, "File is null");
		this.file = file;
	}

	public InputStream openInputStream() {
		try {
			return file.openInputStream();
		} catch (FileSystemException e) {
			throw new InputOutputException("Could not open '" + file + "' for reading", e);
		}
	}

	@Override
	public File copy(Path destinationPath) {
		Argument.isNotNull(destinationPath, "Destination path is null");
		return file.copy(destinationPath);
	}

	public URL getUrl() {
		return file.getPath().toURL();
	}

	public String getName() {
		return file.getPath().toString();
	}

	@Override
	public long getContentLength() {
		return file.getSize();
	}

	@Override
	public long getModificationTimestamp() {
		return file.getModificationTimestamp();
	}
}
